<template>
  <dw-page-warpper style="position: relative">
    <div ref="container" style="height: 100%; width: 100%"></div>
  </dw-page-warpper>
</template>
<script setup lang="ts">
import ComponentTest from './component-test.vue';
defineOptions({
  name: 'DwReport',
});
import { onMounted, onBeforeUnmount, ref, toRaw } from 'vue';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { createUniver, defaultTheme, LocaleType, merge, Univer } from '@univerjs/presets';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import UniverPresetSheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';

import '@univerjs/presets/lib/styles/preset-sheets-core.css';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { UniverSheetsDrawingPreset } from '@univerjs/presets/preset-sheets-drawing';

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import sheetsZenEditorZhCN from '@univerjs/sheets-zen-editor/locale/zh-CN';

import '@univerjs/sheets-zen-editor/lib/index.css';

import '@univerjs/sheets-zen-editor/facade';

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { UniverSheetsCrosshairHighlightPlugin } from '@univerjs/sheets-crosshair-highlight';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import UniverSheetsCrosshairHighlightZhCN from '@univerjs/sheets-crosshair-highlight/locale/zh-CN';

import '@univerjs/sheets-crosshair-highlight/lib/index.css';

import '@univerjs/sheets-crosshair-highlight/facade';

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { UniverSheetsDataValidationPreset } from '@univerjs/presets/preset-sheets-data-validation';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import UniverPresetSheetsDataValidationZhCN from '@univerjs/presets/preset-sheets-data-validation/locales/zh-CN';

const container = ref<HTMLElement | null>(null);

const univerAPIRef = ref<Univer | null>(null);
const collaboration = undefined;

// const Vue3Component = defineComponent({
//   setup(props) {
//     console.log('Vue3Component', props)
//     return () => <div style="{{ width: 100, height: 100, background: '#fff' }}">弹出内容</div>
//   },
// })

onMounted(() => {
  const { univerAPI } = createUniver({
    locale: LocaleType.ZH_CN,
    locales: {
      [LocaleType.ZH_CN]: merge({}, UniverPresetSheetsCoreZhCN, sheetsZenEditorZhCN, UniverPresetSheetsDataValidationZhCN, UniverPresetSheetsDataValidationZhCN, UniverSheetsCrosshairHighlightZhCN),
    },
    theme: defaultTheme,

    presets: [
      UniverSheetsCorePreset({
        container: container.value!,
        header: true,
        footer: true,
      }),
      UniverSheetsDrawingPreset({
        collaboration,
      }),
      UniverSheetsDataValidationPreset(),
    ],
    plugins: [UniverSheetsCrosshairHighlightPlugin, UniverSheetsZenEditorPlugin],
  });

  univerAPI.createWorkbook({
    name: 'Test Sheet',
    sheets: {
      sheet1: {
        id: 'sheet1',
        name: '数据库字段标准',
        cellData: {
          0: {
            0: {
              v: 'Hello Univer!',
            },
          },
        },
        defaultRowHeight: 32,
        rowCount: 100,
        columnCount: 10,
      },
    },
  });

  univerAPI.registerComponent('myComponentKey', ComponentTest, {
    framework: 'vue3',
  });

  univerAPI.executeCommand('sheet.command.set-range-values', {
    value: { v: 'Hello, Univer!' },
    range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },
  });

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  univerAPI.addEvent(univerAPI.Event.BeforeSheetEditStart, (params) => {
    const { row, column } = params;
    console.log(`单元格被点击，行：${row}，列：${column}`);
    const workbook = univerAPI.getActiveWorkbook();
    const sheet = workbook!.getActiveSheet();
    debugger;
    const range1 = sheet.getRange(params.row, params.column);
    range1.attachPopup({
      // componentKey 必须是一个组件或已注册组件的键
      componentKey: 'myComponentKey',
    });
    // if (row === 1) {
    //   try {
    //     params.cancel = true
    //   } catch (ex) {
    //     console.log(ex)
    //   }
    // }
    // univerAPI.openDialog({
    //   // unique id
    //   id: 'myComponentKey',
    //   draggable: true,
    //   width: 300,
    //   title: { title: 'Dialog title' },
    //   children: {
    //     label: 'myComponentKey',
    //   },
    //   destroyOnClose: true,
    //   preservePositionOnDestroy: true,
    //   onClose: () => {},
    // })
  });
  univerAPI.addEvent(univerAPI.Event.BeforeSheetEditStart, (params) => {
    const { row, column } = params;
    console.log(`单元格被点击，行：${row}，列：${column}`);
    const workbook = univerAPI.getActiveWorkbook();
    const sheet = workbook!.getActiveSheet();
    debugger;
    const range1 = sheet.getRange(params.row, params.column);
    const popup = range1.attachPopup({
      // componentKey 必须是一个组件或已注册组件的键
      componentKey: 'myComponentKey',
    });
    setTimeout(() => {
      popup!.dispose();
    }, 2000);
    // if (row === 1) {
    //   try {
    //     params.cancel = true
    //   } catch (ex) {
    //     console.log(ex)
    //   }
    // }
    // univerAPI.openDialog({
    //   // unique id
    //   id: 'myComponentKey',
    //   draggable: true,
    //   width: 300,
    //   title: { title: 'Dialog title' },
    //   children: {
    //     label: 'myComponentKey',
    //   },
    //   destroyOnClose: true,
    //   preservePositionOnDestroy: true,
    //   onClose: () => {},
    // })
  });

  // 注册监听器
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  // univerAPI.onBeforeCommandExecute((command) => {
  //   // 在命令执行前执行自定义逻辑
  //   const { id, type, params } = command
  //   console.log(id)
  //   console.log(type)
  //   console.log(params)
  //   throw new Error('禁止编辑')
  // })

  setDataValidation(univerAPI);
  // univerAPI.setCrosshairHighlightEnabled(true)
  // const newRuleRange = worksheet.getRange('C1:D10')
  // fRange1
  //   .getDataValidation()
  //   // 更改新的范围 C1:D10
  //   .setRanges([newRuleRange])
  //   // 更改新的条件，要求数字在 1 到 10 之间
  //   .setCriteria(univerAPI.Enum.DataValidationType.DECIMAL, [
  //     univerAPI.Enum.DataValidationOperator.BETWEEN,
  //     '1',
  //     '10',
  //   ])
  //   // 更改验证选项，当输入不符合条件时停止输入并显示错误消息
  //   .setOptions({
  //     allowBlank: true,
  //     showErrorMessage: true,
  //     error: '输入的值无效',
  //     // errorStyle: univerAPI.Enum.DataValidationErrorStyle.STOP,
  //   })

  // worksheet.setFrozenColumns(2)
  // worksheet.setFrozenRows(1)
  // // const fWorkbook = univerAPI.getActiveWorkbook()
  // // const themes = fWorkbook.getRegisteredRangeThemes()
  // // console.log(themes)
  // const fRange = worksheet.getRange('A:E')
  // fRange.useThemeStyle('light-blue') // 使用默认主题
  functionsetWorksheetPermission(univerAPI);
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
const setDataValidation = (univerAPI) => {
  const worksheet = univerAPI.getActiveWorkbook().getActiveSheet();

  const fRange1 = worksheet.getRange('A1:B10');

  const rule = univerAPI
    .newDataValidation()
    .requireNumberBetween(1, 10)
    .setOptions({
      allowBlank: true,
      showErrorMessage: true,
      error: '值必须再1到10之间',
    })
    .build();
  fRange1.setDataValidation(rule);
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
const functionsetWorksheetPermission = async (univerAPI) => {
  const workbook = univerAPI.getActiveWorkbook();
  const sheet = workbook.getActiveSheet();
  const unitId = workbook.getId();
  const subUnitId = sheet.getSheetId();

  const range1 = sheet.getRange('A1:G1');
  const range2 = sheet.getRange('C4:D5');
  const ranges = [range1, range2];
  range1.setValue(2);

  const permission = univerAPI.getPermission();
  const rangeProtectionPermissionEditPoint = permission.permissionPointsDefinition.RangeProtectionPermissionEditPoint;
  const res = await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
  // 这里的返回区别于工作表权限，因为一个子表中可能会有多个区域保护，所以 ruleId 是用来存储该权限规则的唯一 id，permissionId 是用来拼接权限点位的。
  const { permissionId } = res;
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  permission.rangeRuleChangedAfterAuth$.subscribe((currentPermissionId) => {
    if (currentPermissionId === permissionId) {
      // 设置范围保护为不可编辑
      permission.setRangeProtectionPermissionPoint(unitId, subUnitId, permissionId, rangeProtectionPermissionEditPoint, false);
    }
  });

  permission.setPermissionDialogVisible(false);

  // const workbook = univerAPI.getActiveWorkbook() // 获取当前活动的工作簿
  // const unitId = workbook.getId() // 获取工作簿
  // const subUnitId = workbook.getActiveSheet().getSheetId() // 获取当前活动工作表的 ID
  // const permission = univerAPI.getPermission() // 获取权限模块

  // const worksheetEditPermission = permission.permissionPointsDefinition.WorksheetEditPermission
  // // 创建基础工作表权限
  // const permissionId = await permission.addWorksheetBasePermission(unitId, subUnitId)
  // // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // //@ts-ignore
  // permission.sheetRuleChangedAfterAuth$.subscribe((currentPermissionId) => {
  //   if (currentPermissionId === permissionId) {
  //     // 设置工作表为不可编辑状态

  //     permission.setWorksheetPermissionPoint(unitId, subUnitId, worksheetEditPermission, false)
  //   } else {

  //   }
  // })
};

onBeforeUnmount(() => {
  toRaw(univerAPIRef.value)?.dispose();
  univerAPIRef.value = null;
});
</script>
